package com.unis.controller.system;

import com.unis.common.excel.ExportBeanExcel;
import com.unis.common.exception.http.RequestEntityTooLargeException;
import com.unis.common.util.ValidateUtil;
import com.unis.controller.BaseController;
import com.unis.dto.ResultDto;
import com.unis.logger.TargetLogger;
import com.unis.model.system.Permission;
import com.unis.service.system.PermissionService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/8/008.
 */
@Controller
@RequestMapping("/system/permission")
public class PermissionController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PermissionController.class);

    @Autowired
    private PermissionService permissionService;
    @RequiresPermissions("SYS_PERM")
    @RequestMapping("/page")
    public String forwordPage()  {
        return "system/permission/permissionPage";
    }

    @TargetLogger("030401")
    @RequiresPermissions("SYS_PERM")
    @RequestMapping( "/list")
    @ResponseBody
    public ResultDto queryPermissionList(@RequestParam Map<?, ?> paramMap){
        int pageSize = paramMap.get("pageSize")==null ? 10 : Integer.parseInt(paramMap.get("pageSize").toString());
        int pageNumber = paramMap.get("pageNumber")==null ? 1 : Integer.parseInt(paramMap.get("pageNumber").toString());
        try {
            ResultDto page = permissionService.queryListByPage(paramMap,pageNumber,pageSize);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @TargetLogger("030402")
    @RequiresPermissions("SYS_PERM")
    @RequestMapping("/excel")
    public void exportPermissionList(HttpServletResponse response, @RequestParam Map<?, ?> paramMap){
        //导出默认1000行
        int pageSize = EXPORT_SIZE;
        int pageNumber = 1;
        OutputStream os = null;
        try {
            ResultDto page = permissionService.queryListByPage(paramMap,pageNumber,pageSize);
            List list = page.getRows();

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=exportPermission"+ System.currentTimeMillis() + ".xls");
            os = response.getOutputStream();

            ExportBeanExcel<Permission> export = new ExportBeanExcel<Permission>();
            //根据需求选择导出字段，注意数据库中带有_等字符字段修改
            //导出表头
            String[] headers = {"权限代码","权限名称","权限描述"};
            //对应字段 headers 与cols一一对应
            String[] cols = {"code","name","comments"};

            export.exportExcel("系统权限",headers,cols,list,os);

            os.flush();
            os.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @TargetLogger("0301")
    @RequiresPermissions("SYS_PERM")
    @RequestMapping("/curd")
    @ResponseBody
    public Map<String,String> curd(String curdType,Permission permission) throws Exception {
        Map<String,String> resultMap = new HashMap<>();
        String msg = null;
        if (permission!=null){
            if (StringUtils.equalsIgnoreCase(curdType,"insert")){
                //valid校验需在Permission的字段上增加校验规则，规则与表单规则保持一致
                msg = ValidateUtil.valid(permission);
                if (StringUtils.isNotBlank(msg)){
                    logger.error("valid insert Permission is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
                permissionService.insert(permission);
            }else if (StringUtils.equalsIgnoreCase(curdType,"delete")){
                if(StringUtils.isNotBlank(permission.getPk())) {
                    permissionService.delete(permission.getPk()); //主键删除
                }else {
                    msg="没有要删除的数据";
                    logger.error("valid delete Permission is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
            }else if (StringUtils.equalsIgnoreCase(curdType,"update")){
                msg = ValidateUtil.valid(permission);
                if (StringUtils.isNotBlank(msg)){
                    logger.error("valid update Permission is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
                permissionService.updateByPrimaryKey(permission);
            }
            msg = "操作成功";
        }else{
            msg="信息未填写";
            logger.error(msg);
        }
        resultMap.put("msg",msg);
        return resultMap;
    }
    @RequiresPermissions("SYS_PERM")
    @RequestMapping("/rolePage")
    public String forwordRolePage(){
        return "system/permission/rolePermissionPage";
    }
    @RequiresPermissions("SYS_PERM")
    @RequestMapping("/deptPage")
    public String forwordDeptPage(){
        return "system/permission/deptPermissionPage";
    }
    @RequiresPermissions("SYS_PERM")
    @RequestMapping("/userPage")
    public String forwordUserPage(){
        return "system/permission/userPermissionPage";
    }
    @RequiresPermissions("SYS_PERM")
    @RequestMapping("/menuPage")
    public String forwordMenuPage(){
        return "system/permission/menuPermissionPage";
    }

    @TargetLogger("03050101")
    @RequiresPermissions("SYS_PERM")
    @RequestMapping( "/relatList")
    @ResponseBody
    public List<Map<String,String>> queryRelatList(@RequestParam Map<?, ?> paramMap){
        //int pageSize = paramMap.get("pageSize")==null ? 10 : Integer.parseInt(paramMap.get("pageSize").toString());
        //int pageNumber = paramMap.get("pageNumber")==null ? 1 : Integer.parseInt(paramMap.get("pageNumber").toString());

        //cType 权限类别，标记为角色权限ROLE、单位权限DEPT、用户权限USER、菜单MENU
        //foreingKey 关联  cType=ROLE:T_SYS_ROLE.CODE   cType=DEPT:T_SYS_DEPARTMENT.DEPTCODE  cType=USER:T_SYS_ACCOUNT.PK  cType=MENU:T_SYS_MENU.CODE
        String cType=paramMap!=null && paramMap.get("cType")!=null && StringUtils.isNotBlank(paramMap.get("cType").toString())?paramMap.get("cType").toString():null;
        String foreingKey=paramMap!=null && paramMap.get("foreingKey")!=null && StringUtils.isNotBlank(paramMap.get("foreingKey").toString())?paramMap.get("foreingKey").toString():null;
        String permType=paramMap!=null && paramMap.get("permType")!=null && StringUtils.isNotBlank(paramMap.get("permType").toString())?paramMap.get("permType").toString():null;
        try {
            List<Map<String,String>> list = permissionService.queryListByType(cType,foreingKey,permType);
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @TargetLogger("03050102")
    @RequiresPermissions("SYS_PERM")
    @RequestMapping("/relatPerm")
    @ResponseBody
    public Map<String,String> relatPerm(String cType,String foreingKey,String relatCheckedCode,String permType){
        Map<String,String> resultMap = new HashMap<>();
        String msg = null;
        if(StringUtils.isNotBlank(cType) && StringUtils.isNotBlank(foreingKey)){
            try {
                permissionService.relatPerm(cType, foreingKey, relatCheckedCode,permType);
                msg="授权成功";
                resultMap.put("msg",msg);
            } catch (Exception e) {
                logger.error(e.getMessage());
                throw new RequestEntityTooLargeException(e.getMessage());
            }

        }else{
            msg="信息未填写";
            logger.error(msg);
        }
        resultMap.put("msg",msg);
        return resultMap;
    }

}
